package com.example.xinyun.domain;

import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.ByteArrayOutputStream;

public class convert {
    public static byte[] PixelMapToBytes(PixelMap pixelMap) {
        //PixelMap pm = image.getPixelMap();
        ImagePacker imagePacker = ImagePacker.create();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
        imagePacker.initializePacking(byteArrayOutputStream, packingOptions);
        imagePacker.addImage(pixelMap);
        imagePacker.finalizePacking();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        return bytes;
    }

    public static PixelMap ByteToPixelMap(byte[] bytes) {
        // 用于 ImageSource的 create(bytes,srcOpts)方法
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        //设置图片原格式也可以用 null
        srcOpts.formatHint = "image/jpeg";
        ImageSource imageSource = ImageSource.create(bytes, srcOpts);
        //通过ImageSource创建 PixelMap文件
        PixelMap pixelMap = imageSource.createPixelmap(null);
        return pixelMap;
    }
}
